import { createRouter, createWebHistory } from 'vue-router'
import HomePage from '@/views/Home/index.vue'
import { isLogin } from '@/utils/user'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/home'
    },
    {
      path: '/home',
      component: HomePage,
      name: 'home'
    },
    {
      path: '/cate',
      component: () => import('@/views/Cate/index.vue'),
      name: 'cate'
    },
    {
      path: '/cart',
      component: () => import('@/views/Cart/index.vue'),
      meta: {
        needLogin: true
      },
      name: 'cart'
    },
    {
      path: '/user',
      component: () => import('@/views/User/index.vue'),
      meta: {
        needLogin: true
      },
      name: 'user'
    },
    {
      path: '/detail',
      component: () => import('@/views/Detail/index.vue'),
      name: 'detail'
    },
    {
      path: '/itemLists/:cateId',
      component: () => import('@/views/ItemLists/index.vue'),
      name: 'itemLists'
    },
    {
      path: '/login',
      component: () => import('@/views/Login/index.vue'),
      name: 'login'
    },
    {
      path: '/reg',
      component: () => import('@/views/Register/index.vue'),
      name: 'reg'
    }
  ]
})
router.beforeEach(((to, from) => {
  // 判断是否需要登录
  if (to.meta.needLogin) {
    if (!isLogin()) {
      return {
        path: '/login',
        query: {
          redirect: to.fullPath
        }
      }
    
    }
  }
}))
export default router
